package net.sevear.chaos.douban.shuo
{
	import com.adobe.serialization.json.JSON;
	
	import de.popforge.utils.SprintfUtil;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.sampler.startSampling;
	
	import net.sevear.chaos.utils.Logger;
	
	public class DBShuoTimeLine extends EventDispatcher
	{
		private var loader:URLLoader;
		
		private static const TIME_LINE_URI:String = "http://shuo.douban.com/api/statuses/user_timeline/%s?until_id=%d";
		private static const TIME_LINE_NEWEST_URI:String = "http://shuo.douban.com/api/statuses/user_timeline/%s";
		private var _userUID:String;
		
		public function DBShuoTimeLine(userUID:String)
		{
			super(null);
			_userUID = userUID;
			loader = new URLLoader();
			loader.addEventListener(Event.COMPLETE,onLoadComplete);
			loader.addEventListener(IOErrorEvent.IO_ERROR,onIOErr);
		}
		
		public function loadTimeLine(startID:int):void{
			try{
				loader.close();
			}catch(e:Error){
				
			}
			if(startID == -1){
				loader.load(new URLRequest(SprintfUtil.sprintf(TIME_LINE_NEWEST_URI,_userUID)));
			}else{
				loader.load(new URLRequest(SprintfUtil.sprintf(TIME_LINE_URI,_userUID,startID)));
			}
			
		}
		
		public function stopLoad():void{
			try{
				loader.close();
			}catch(e:Error){
				
			}
		}
		
		private function onLoadComplete(e:Event):void{
			try{
				var rst:Object = JSON.decode((e.currentTarget as URLLoader).data as String);
				var lastId:int;
				if(rst.length>0){
					var lastObj:Object = (rst as Array)[rst.length-1];
					lastId = lastObj.id;
				}else{
					lastId = 0;
				}
				dispatchEvent(new DBShuoEvent(DBShuoEvent.TIME_LINE_UPDATED,{result:rst,lastID:lastId}));
			}catch(err:Error){
				Logger.getInstance().logError("error when getting timeline of ",_userUID," in DouBanShuo: ",err.message);
				dispatchEvent(new DBShuoEvent(DBShuoEvent.TIME_LINE_UPDATED_FAILED,_userUID));
			}
		}
		
		private function onIOErr(e:IOErrorEvent):void{
			Logger.getInstance().logError("error when getting timeline of ",_userUID," in DouBanShuo");
			dispatchEvent(new DBShuoEvent(DBShuoEvent.TIME_LINE_UPDATED_FAILED,_userUID));
		}
	}
}